// ignore_for_file: library_private_types_in_public_api, use_build_context_synchronously
import 'dart:io';
import 'package:number_paginator/number_paginator.dart';
import 'package:path_provider/path_provider.dart';
import 'package:sp_util/sp_util.dart';
import 'package:syncfusion_flutter_datagrid_export/export.dart';
import 'package:syncfusion_flutter_xlsio/xlsio.dart' as xlsio;
import 'package:flutter/material.dart';
import 'package:flutter_styled_toast/flutter_styled_toast.dart';
import 'package:intl/intl.dart';
import 'package:storage/database.dart';
import 'package:storage/dialog/add_and_edit_goods_dialog.dart';
import 'package:storage/model/bind_good_and_company_model_entity.dart';
import 'package:storage/model/company_model_entity.dart';
import 'package:storage/model/user_name_entity.dart';
import 'package:storage/model/warehouse_in_out_model_entity.dart';
import 'package:storage/pages/all_company_page.dart';
import 'package:storage/source/all_goods_source.dart';
import 'package:storage/source/every_company_count_page.dart';
import 'package:storage/widget/int_input_formatter.dart';
import 'package:syncfusion_flutter_datagrid/datagrid.dart';

class AllGoodsPage extends StatefulWidget {
  const AllGoodsPage({super.key});

  @override
  _AllGoodsPageState createState() => _AllGoodsPageState();
}

class _AllGoodsPageState extends State<AllGoodsPage> {
  List<UserNameEntity> modelList = [];
  late AllGoodsDataSource employeeDataSource;
  final TextEditingController _searchController = TextEditingController();
  final TextEditingController _warehouseInOutController =
      TextEditingController();

  @override
  void dispose() {
    _searchController.dispose();
    _warehouseInOutController.dispose();
    _controller.dispose();
    super.dispose();
  }

  bool needPage = false;

  @override
  void initState() {
    super.initState();
    WidgetsBinding.instance.addPostFrameCallback((timeStamp) async {
      needPage = SpUtil.getBool('needPage') ?? false;
      refreshData();
    });
  }

  int pageNum = 1;
  int pageSize = 20;
  int total = 0;
  String? warehouseInDate;
  String? warehouseOutDate;

  Future<void> refreshData() async {
    CommonListModel result = await DatabaseHelper().getGoodsList(
        goodName: _searchController.text,
        pageNum: needPage ? pageNum : null,
        pageSize: needPage ? pageSize : null,
        warehouseInDate: warehouseInDate,
        warehouseOutDate: warehouseOutDate);
    total = (result.total / pageSize).ceil();

    modelList = result.data.map((e) => UserNameEntity.fromJson(e)).toList();
    employeeDataSource = AllGoodsDataSource(employeeData: modelList);
    selectedIdList.clear();
    setState(() {});
  }

  final NumberPaginatorController _controller = NumberPaginatorController();

  Widget _buildBottomNumberPagination() {
    return NumberPaginator(
      config: const NumberPaginatorUIConfig(
          mainAxisAlignment: MainAxisAlignment.center),
      controller: _controller,
      // by default, the paginator shows numbers as center content
      numberPages: total,
      onPageChange: (int index) {
        pageNum = index + 1;
        refreshData();
      },
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('库存明细'),
      ),
      body: Container(
        color: Colors.white,
        padding: const EdgeInsets.all(20),
        child: Column(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          children: [
            Expanded(
              child: Column(
                children: [
                  Row(
                    children: [
                      SizedBox(
                        width: 200,
                        height: 40,
                        child: TextField(
                          controller: _searchController,
                          maxLines: 1,
                          onSubmitted: (value) {
                            refreshData();
                          },
                          decoration: InputDecoration(
                              border: OutlineInputBorder(
                                borderSide: const BorderSide(
                                    width: 2.0, color: Colors.black),
                                // 边框样式
                                borderRadius:
                                    BorderRadius.circular(10.0), // 设置圆角半径
                              ),
                              hintText: '请输入商品名称搜索',
                              hintStyle: const TextStyle(color: Colors.grey)),
                        ),
                      ),

                      const SizedBox(width: 10),

                      // 选择时间段按钮
                      GestureDetector(
                        onTap: () async {
                          DateTime? pickedDate = await showDatePicker(
                            context: context,
                            firstDate: DateTime(2000),
                            lastDate: DateTime(2100),
                            currentDate: DateTime.now(),
                          );

                          if (pickedDate != null) {
                            setState(() {
                              warehouseInDate =
                                  DateFormat('yyyy-MM-dd').format(pickedDate);
                            });
                          }
                        },
                        child: Container(
                          padding: const EdgeInsets.symmetric(
                              horizontal: 10, vertical: 8),
                          decoration: BoxDecoration(
                            border: Border.all(color: Colors.black, width: 2),
                            borderRadius: BorderRadius.circular(10),
                          ),
                          child: Row(
                            children: [
                              const Icon(Icons.date_range, color: Colors.black),
                              const SizedBox(width: 5),
                              Text(
                                warehouseInDate != null
                                    ? warehouseInDate!
                                    : "选择入库时间",
                                style: const TextStyle(color: Colors.black),
                              ),
                            ],
                          ),
                        ),
                      ),

                      const SizedBox(width: 10), // 选择时间按钮
                      GestureDetector(
                        onTap: () async {
                          DateTime? pickedDate = await showDatePicker(
                            context: context,
                            firstDate: DateTime(2000),
                            lastDate: DateTime(2100),
                            currentDate: DateTime.now(),
                          );

                          if (pickedDate != null) {
                            setState(() {
                              warehouseOutDate =
                                  DateFormat('yyyy-MM-dd').format(pickedDate);
                            });
                          }
                        },
                        child: Container(
                          padding: const EdgeInsets.symmetric(
                              horizontal: 10, vertical: 8),
                          decoration: BoxDecoration(
                            border: Border.all(color: Colors.black, width: 2),
                            borderRadius: BorderRadius.circular(10),
                          ),
                          child: Row(
                            children: [
                              const Icon(Icons.date_range, color: Colors.black),
                              const SizedBox(width: 5),
                              Text(
                                warehouseOutDate != null
                                    ? warehouseOutDate!
                                    : "选择出库时间",
                                style: const TextStyle(color: Colors.black),
                              ),
                            ],
                          ),
                        ),
                      ),

                      const SizedBox(width: 10),
                      FilledButton(
                          onPressed: () {
                            /// 搜索
                            refreshData();
                          },
                          child: const Text('搜索')),
                      const SizedBox(width: 10),
                      FilledButton(
                          onPressed: () {
                            _searchController.clear();
                            warehouseInDate = null;
                            warehouseOutDate = null;
                            refreshData();
                          },
                          child: const Text('重置')),
                    ],
                  ),
                  const SizedBox(height: 20),
                  Row(
                    children: [
                      FilledButton(
                          onPressed: () {
                            showAddDialog();
                          },
                          child: const Text('新增')),
                      const SizedBox(width: 10),
                      FilledButton(
                          onPressed: selectedIdList.isEmpty
                              ? null
                              : () async {
                                  if (selectedIdList.isEmpty) {
                                    showToast('请选择需要修改的商品', context: context);
                                    return;
                                  }
                                  showAddDialog(
                                      model: modelList.firstWhere((element) =>
                                          element.goodsId ==
                                          selectedIdList.first));
                                },
                          child: const Text('修改')),
                      const SizedBox(width: 10),
                      FilledButton(
                          onPressed: selectedIdList.isEmpty
                              ? null
                              : () async {
                                  if (selectedIdList.isEmpty) {
                                    showToast('请选择需要删除的商品', context: context);
                                    return;
                                  }
                                  bool show = await deleteDialog();
                                  if (show) {
                                    await DatabaseHelper()
                                        .deleteGood(selectedIdList);
                                    refreshData();
                                  }
                                },
                          child: const Text('删除')),
                      const SizedBox(width: 10),
                      FilledButton(
                          onPressed: selectedIdList.isEmpty
                              ? null
                              : () async {
                                  warehouseInDialog(
                                      model: modelList.firstWhere((element) =>
                                          element.goodsId ==
                                          selectedIdList.first));
                                },
                          child: const Text('入库')),
                      const SizedBox(width: 10),
                      FilledButton(
                          onPressed: selectedIdList.isEmpty
                              ? null
                              : () async {
                                  await warehouseOutDialog(
                                      model: modelList.firstWhere((element) =>
                                          element.goodsId ==
                                          selectedIdList.first),
                                      isWarehouseOut: true);
                                },
                          child: const Text('出库')),
                      const SizedBox(width: 10),
                      FilledButton(
                          onPressed: selectedIdList.isEmpty
                              ? null
                              : () async {
                                  await warehouseOutDialog(
                                      model: modelList.firstWhere((element) =>
                                          element.goodsId ==
                                          selectedIdList.first),
                                      isWarehouseOut: false);
                                },
                          child: const Text('绑定各公司报价')),
                      const SizedBox(width: 10),
                      FilledButton(
                          onPressed: () {
                            exportDataGridToExcel();
                          },
                          child: const Text('导出excel')),
                    ],
                  ),
                  const SizedBox(height: 20),
                  if (modelList.isNotEmpty)
                    Expanded(
                      child: SfDataGrid(
                        key: _key,
                        source: employeeDataSource,
                        rowHeight: 40,
                        headerRowHeight: 40,
                        columnWidthMode: ColumnWidthMode.fill,
                        showCheckboxColumn: true,
                        selectionMode: SelectionMode.single,
                        //开启列宽度调节
                        allowColumnsResizing: true,
                        onSelectionChanged: onSelectionChanged,
                        columns: <GridColumn>[
                          GridColumn(
                              columnName: '商品id',
                              label: Container(
                                  padding: const EdgeInsets.all(8),
                                  alignment: Alignment.center,
                                  decoration: const BoxDecoration(
                                      color: Colors.lightBlueAccent,
                                      border: Border(
                                        right: BorderSide(
                                            color: Colors.grey, width: 1),
                                        left: BorderSide(
                                            color: Colors.grey, width: 1),
                                      )),
                                  child: const Text(
                                    '商品id',
                                  ))),
                          GridColumn(
                              columnName: '商品名称',
                              label: Container(
                                  padding: const EdgeInsets.all(8),
                                  alignment: Alignment.center,
                                  decoration: const BoxDecoration(
                                      color: Colors.lightBlueAccent,
                                      border: Border(
                                        right: BorderSide(
                                            color: Colors.grey, width: 1),
                                        left: BorderSide(
                                            color: Colors.grey, width: 1),
                                      )),
                                  child: const Text(
                                    '商品名称',
                                  ))),
                          GridColumn(
                              columnName: '商品规格',
                              label: Container(
                                  padding: const EdgeInsets.all(8),
                                  alignment: Alignment.center,
                                  decoration: const BoxDecoration(
                                      color: Colors.lightBlueAccent,
                                      border: Border(
                                        right: BorderSide(
                                            color: Colors.grey, width: 1),
                                        left: BorderSide(
                                            color: Colors.grey, width: 1),
                                      )),
                                  child: const Text(
                                    '商品规格',
                                  ))),
                          GridColumn(
                              columnName: '商品价格',
                              label: Container(
                                  padding: const EdgeInsets.all(8),
                                  alignment: Alignment.center,
                                  decoration: const BoxDecoration(
                                      color: Colors.lightBlueAccent,
                                      border: Border(
                                        right: BorderSide(
                                            color: Colors.grey, width: 1),
                                        left: BorderSide(
                                            color: Colors.grey, width: 1),
                                      )),
                                  child: const Text(
                                    '商品价格',
                                  ))),
                          GridColumn(
                              columnName: '库存数量',
                              label: Container(
                                  padding: const EdgeInsets.all(8),
                                  alignment: Alignment.center,
                                  decoration: const BoxDecoration(
                                      color: Colors.lightBlueAccent,
                                      border: Border(
                                        right: BorderSide(
                                            color: Colors.grey, width: 1),
                                        left: BorderSide(
                                            color: Colors.grey, width: 1),
                                      )),
                                  child: const Text(
                                    '库存数量',
                                  ))),
                          GridColumn(
                              columnName: '上次修改价格',
                              label: Container(
                                  padding: const EdgeInsets.all(8.0),
                                  alignment: Alignment.center,
                                  decoration: const BoxDecoration(
                                      color: Colors.lightBlueAccent,
                                      border: Border(
                                        right: BorderSide(
                                            color: Colors.grey, width: 1),
                                        left: BorderSide(
                                            color: Colors.grey, width: 1),
                                      )),
                                  child: const Text('上次修改价格'))),
                          GridColumn(
                              columnName: '上次入库时间',
                              label: Container(
                                  padding: const EdgeInsets.all(8.0),
                                  alignment: Alignment.center,
                                  decoration: const BoxDecoration(
                                      color: Colors.lightBlueAccent,
                                      border: Border(
                                        right: BorderSide(
                                            color: Colors.grey, width: 1),
                                        left: BorderSide(
                                            color: Colors.grey, width: 1),
                                      )),
                                  child: const Text(
                                    '上次入库时间',
                                    overflow: TextOverflow.ellipsis,
                                  ))),
                          GridColumn(
                              columnName: '上次出库时间',
                              label: Container(
                                  padding: const EdgeInsets.all(8.0),
                                  alignment: Alignment.center,
                                  decoration: const BoxDecoration(
                                      color: Colors.lightBlueAccent,
                                      border: Border(
                                        right: BorderSide(
                                            color: Colors.grey, width: 1),
                                        left: BorderSide(
                                            color: Colors.grey, width: 1),
                                      )),
                                  child: const Text('上次出库时间'))),
                        ],
                      ),
                    ),
                ],
              ),
            ),
            if (needPage && total > 0) _buildBottomNumberPagination()
          ],
        ),
      ),
    );
  }

  final GlobalKey<SfDataGridState> _key = GlobalKey<SfDataGridState>();

  /// 导出excel
  Future<void> exportDataGridToExcel() async {
    // 获取当前应用的文档目录
    Directory documentsDirectory = await getApplicationDocumentsDirectory();

    // 创建一个名为“excel汇总”的子文件夹，如果不存在则创建
    Directory excelSummaryDirectory =
        Directory('${documentsDirectory.path}/excel汇总');
    if (!await excelSummaryDirectory.exists()) {
      await excelSummaryDirectory.create();
    }

    // 导出 SfDataGrid 数据到 Excel
    final xlsio.Workbook workbook = _key.currentState!.exportToExcelWorkbook(
      excludeColumns: ['商品id'],
    );
    final List<int> bytes = workbook.saveAsStream();
    workbook.dispose();

    // 生成唯一的文件名，避免覆盖同名文件
    String fileName = '库存明细表_${DateTime.now().millisecondsSinceEpoch}.xlsx';
    File file = File('${excelSummaryDirectory.path}/$fileName');

    // 将文件写入到指定路径
    await file.writeAsBytes(bytes);

    showToast('库存明细表导出成功', context: context);
  }

  List<int> selectedIdList = [];

  // 表格选择事件改变回调
  void onSelectionChanged(
      List<DataGridRow> addedRows, List<DataGridRow> removedRows) {
    if (addedRows.isEmpty && removedRows.isEmpty) {
      for (DataGridRow row in employeeDataSource.rows) {
        int id = row.getCells().first.value as int;
        selectedIdList.remove(id);
      }
    }
    for (DataGridRow addedRow in addedRows) {
      int id = addedRow.getCells().first.value as int;
      if (!selectedIdList.contains(id)) {
        selectedIdList.add(id);
      }
    }
    for (DataGridRow removedRow in removedRows) {
      int id = removedRow.getCells().first.value as int;

      selectedIdList.remove(id);
    }
    setState(() {});
  }

  /// 添加/修改商品dialog
  void showAddDialog({UserNameEntity? model}) {
    showDialog(
        context: context,
        builder: (_) => Dialog(
              shape: RoundedRectangleBorder(
                borderRadius: BorderRadius.circular(10.0),
              ),
              elevation: 0, // 移除阴影以符合定制大小的需求
              child:
                  AddAndEditGoodsDialog(model: model, refreshData: refreshData),
            ));
  }

  /// 选中的公司modelList
  List<CompanyModelEntity> selectedCompanyModelList = [];

  /// 出库和绑定公司用一个dialog
  Future<void> warehouseOutDialog(
      {required UserNameEntity model, bool isWarehouseOut = true}) async {
    selectedCompanyModelList.clear();

    /// 先选公司
    await showDialog(
        context: context,
        builder: (_) => Dialog(
              shape: RoundedRectangleBorder(
                borderRadius: BorderRadius.circular(10.0),
              ),
              elevation: 0, // 移除阴影以符合定制大小的需求
              child: AllCompanyPage(
                showButton: false,
                confirmCallBack: (List<CompanyModelEntity> tempModelList) {
                  selectedCompanyModelList = List.from(tempModelList);
                },
              ),
            ));
    if (selectedCompanyModelList.isNotEmpty) {
      /// 选完公司跳转另一个dialog
      await showDialog(
          context: context,
          builder: (_) => Dialog(
                shape: RoundedRectangleBorder(
                  borderRadius: BorderRadius.circular(10.0),
                ),
                elevation: 0, // 移除阴影以符合定制大小的需求
                child: _buildWarehouseOutDialog(model,
                    isWarehouseOut: isWarehouseOut),
              ));
    }
  }

  /// 入库dialog
  void warehouseInDialog({UserNameEntity? model}) {
    showDialog(
        context: context,
        builder: (_) => Dialog(
              shape: RoundedRectangleBorder(
                borderRadius: BorderRadius.circular(10.0),
              ),
              elevation: 0, // 移除阴影以符合定制大小的需求
              child: Padding(
                padding: const EdgeInsets.all(20),
                child: Column(
                  mainAxisSize: MainAxisSize.min,
                  children: [
                    SizedBox(
                      width: 400,
                      child: Row(
                        mainAxisSize: MainAxisSize.min,
                        children: [
                          const Text('入库数量'),
                          const SizedBox(width: 10),
                          Expanded(
                              child: TextField(
                            controller: _warehouseInOutController,
                            inputFormatters: [IntegerInputFormatter()],
                            decoration: InputDecoration(
                                border: OutlineInputBorder(
                                  borderSide: const BorderSide(
                                      width: 2.0, color: Colors.black),
                                  // 边框样式
                                  borderRadius:
                                      BorderRadius.circular(10.0), // 设置圆角半径
                                ),
                                hintText: '填写入库数量',
                                hintStyle: const TextStyle(color: Colors.grey)),
                          )),
                        ],
                      ),
                    ),
                    const SizedBox(
                      height: 20,
                    ),
                    SizedBox(
                      width: 400,
                      child: Row(
                        mainAxisSize: MainAxisSize.min,
                        children: [
                          Expanded(
                              child: FilledButton(
                                  onPressed: () {
                                    Navigator.pop(context);
                                  },
                                  child: const Text('取消'))),
                          const SizedBox(
                            width: 20,
                          ),
                          Expanded(
                              child: FilledButton(
                                  onPressed: () async {
                                    if (_warehouseInOutController
                                        .text.isEmpty) {
                                      showToast('请填写入库数量', context: context);
                                      return;
                                    }
                                    await DatabaseHelper().addWarehouseRecord(
                                        WarehouseInOutModelEntity(
                                      warehouseTime:
                                          DateFormat('yyyy-MM-dd HH:mm:ss')
                                              .format(DateTime.now()),
                                      warehouseType: 0,
                                      goodsId: model?.goodsId,
                                      goodsPrice: model?.goodsPrice,
                                      goodsName: model?.goodsName,
                                      goodsSpecification:
                                          model?.goodsSpecification,
                                      count: int.parse(
                                          _warehouseInOutController.text),
                                    ));
                                    Navigator.pop(context);
                                    refreshData();
                                  },
                                  child: const Text('确定'))),
                        ],
                      ),
                    )
                  ],
                ),
              ),
            ));
  }

  Widget _buildWarehouseOutDialog(UserNameEntity model,
      {required bool isWarehouseOut}) {
    List<WarehouseInOutModelEntity> tempWarehouseModelList = List.generate(
        selectedCompanyModelList.length,
        (index) => WarehouseInOutModelEntity(
              warehouseType: 1,
              warehouseTime:
                  DateFormat('yyyy-MM-dd HH:mm:ss').format(DateTime.now()),
              goodsName: model.goodsName,
          goodsSpecification: model.goodsSpecification,
              goodsPrice: model.goodsPrice,
              goodsId: model.goodsId,
              companyName: selectedCompanyModelList[index].companyName,
              companyId: selectedCompanyModelList[index].companyId,
            ));
    List<BindGoodAndCompanyModelEntity> tempBindModelList = List.generate(
        selectedCompanyModelList.length,
        (index) => BindGoodAndCompanyModelEntity(
              goodsName: model.goodsName,
          goodsSpecification: model.goodsSpecification,
              goodsPrice: model.goodsPrice,
              goodsId: model.goodsId,
              companyName: selectedCompanyModelList[index].companyName,
              companyId: selectedCompanyModelList[index].companyId,
            ));

    return Container(
      padding: const EdgeInsets.all(20),
      height: 700,
      width: isWarehouseOut ? 800 : 600,
      child: Column(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: [
          Expanded(
            child: SingleChildScrollView(
              child: Column(
                mainAxisSize: MainAxisSize.min,
                children: [
                  ...List.generate(
                      selectedCompanyModelList.length,
                      (index) => EveryCompanyCountPage(
                            title:
                                selectedCompanyModelList[index].companyName ??
                                    '',
                            isWarehouseOut: isWarehouseOut,
                            index: index,
                            goodsId: model.goodsId!,
                            companyId:
                                selectedCompanyModelList[index].companyId!,
                            onSubmitCallBack: (int index, double companyPrice,
                                int? count, int? bindId) async {
                              if (isWarehouseOut) {
                                /// 出库
                                tempWarehouseModelList[index].companyPrice =
                                    companyPrice;
                                tempWarehouseModelList[index].count = count;
                              } else {
                                /// 这里是绑定公司报价
                                tempBindModelList[index].companyPrice =
                                    companyPrice;
                                if (bindId != null) {
                                  tempBindModelList[index].id = bindId;
                                }
                              }
                            },
                          ))
                ],
              ),
            ),
          ),
          Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [
              SizedBox(
                  width: isWarehouseOut ? 350 : 250,
                  child: FilledButton(
                    onPressed: () async {
                      if (isWarehouseOut) {
                        /// 新增出库记录
                        for (var model in tempWarehouseModelList) {
                          await DatabaseHelper().addWarehouseRecord(model);
                        }
                      } else {
                        /// 新增报价
                        await DatabaseHelper().addOfferIndo(tempBindModelList);
                      }
                      Navigator.pop(context);
                      refreshData();
                    },
                    child: const Text('确定'),
                  )),
              SizedBox(
                  width: isWarehouseOut ? 350 : 250,
                  child: FilledButton(
                    onPressed: () {
                      Navigator.pop(context);
                    },
                    child: const Text('取消'),
                  )),
            ],
          )
        ],
      ),
    );
  }

  /// 删除dialog
  Future<bool> deleteDialog() async {
    bool returnValue = false;
    await showDialog(
        context: context,
        builder: (_) => Dialog(
              shape: RoundedRectangleBorder(
                borderRadius: BorderRadius.circular(10.0),
              ),
              elevation: 0, // 移除阴影以符合定制大小的需求
              child: Padding(
                padding: const EdgeInsets.all(20),
                child: Column(
                  mainAxisSize: MainAxisSize.min,
                  children: [
                    SizedBox(
                      width: 200,
                      child: Row(
                        mainAxisSize: MainAxisSize.min,
                        children: [
                          const Text('是否确认删除'),
                        ],
                      ),
                    ),
                    const SizedBox(
                      height: 20,
                    ),
                    SizedBox(
                      width: 200,
                      child: Row(
                        mainAxisSize: MainAxisSize.min,
                        children: [
                          Expanded(
                              child: FilledButton(
                                  onPressed: () {
                                    Navigator.pop(context);
                                    returnValue = false;
                                  },
                                  child: const Text('取消'))),
                          const SizedBox(
                            width: 20,
                          ),
                          Expanded(
                              child: FilledButton(
                                  onPressed: () async {
                                    Navigator.pop(context);
                                    returnValue = true;
                                  },
                                  child: const Text('确定'))),
                        ],
                      ),
                    )
                  ],
                ),
              ),
            ));
    return returnValue;
  }
}
